import { ReflectUtil } from "../di"
import { getClassName } from "../common"

export function Value(path: string) {
  return function (target, targetKey: string) {
    if (path == null || path.length == 0) {
      throw new Error(`@Value 非法的 path = ${getClassName(target)}.${targetKey}.${path}`)
    }
    /**
     * 将一个 clazz 上所有的 @Value 合并
     * @Value('${database.username}') username:string
     * @Value('${database.password}') password:string
     * @Value('${database.port}') port:number
     * @Value('${other.a.b.c}') abc:string
     * @Value('${other.a.b.d}') abd:string
     * @Value('${other.a.b.e}') abe:string
     * @Value('${profile}') profile:string
     * props = [
     *   {prop: 'username', type: string, path: '${database.username}'},
     *   {prop: 'password', type: string, path: '${database.password}'},
     *   {prop: 'number', type: number, path: '${database.port}'},
     *   {prop: 'abc', type: string, path: '${other.a.b.c}'},
     *   ...
     *   {prop: 'profile', type: string, path: '${profile}'},
     * ]
     */
    const type = ReflectUtil.getType(target, targetKey)
    const oldProps = ReflectUtil.getValues(target) || []
    const props = [
      ...oldProps,
      {
        prop: targetKey,
        type: type,
        path: path
      }
    ]
    ReflectUtil.defineValue(target, props)
  }
}
